﻿using HY.Common;
using HY.Entity;
using HY.Service;
using HY.Web.Controllers;
using HY.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HY.Web.Areas.Resource.Controllers
{
    public class RentController : BaseController
    {
        RentService rentService = new RentService();
        LocationService service = new LocationService();
        /// <summary>
        /// 托管租赁管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Index(int page, int limit)
        {
            ReturnModel returnModel = new ReturnModel();
            try
            {
                var where = $"IsDeleted=0";
                //var code = Request.Form["Code"];
                //if (!string.IsNullOrWhiteSpace(code))
                //    where += $" AND L.Code like '%{code}%'";
                var tuple = service.GetPageList<RentRecord>("RentRecord", "*", where, page, limit, "CreateDate desc");
                returnModel = base.GetReturnModel(tuple.Item1, tuple.Item2);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                LogHelper.Error(new LogInfo() { UserID = UserInfo.UserID, LogType = LogType.Select, LogMessage = "托管租赁列表" }, ex);
            }
            return Json(returnModel);
        }
        /// <summary>
        /// 自管租赁管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Index2()
        {
            return View();
        }


        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Index2(int page, int limit)
        {
            ReturnModel returnModel = new ReturnModel();
            try
            {
                var where = $"IsDeleted=0";
                //var code = Request.Form["Code"];
                //if (!string.IsNullOrWhiteSpace(code))
                //    where += $" AND L.Code like '%{code}%'";
                var tuple = service.GetPageList<RentRecord2>("RentRecord2", "*", where, page, limit, "CreateDate desc");
                returnModel = base.GetReturnModel(tuple.Item1, tuple.Item2);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                LogHelper.Error(new LogInfo() { UserID = UserInfo.UserID, LogType = LogType.Select, LogMessage = "自管租赁列表" }, ex);
            }
            return Json(returnModel);
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult List(int page, int limit)
        {
            ReturnModel returnModel = new ReturnModel();
            try
            {
                var code = Request.Form["Code"];
                var where = $"L.IsDeleted=0";
                if (!string.IsNullOrWhiteSpace(code))
                    where += $" AND L.Code like '%{code}%'";
                var tuple = service.GetPageList<V_LocationList>("Location L JOIN Storehouse S ON L.StorehouseID=S.ID JOIN Park P ON L.ParkID=P.ID LEFT JOIN SysDept ON L.RentDeptID=SysDept.ID", "L.ID,L.Code,L.Area,L.Height,L.Length,L.Width,L.IsRented,L.RentDeptID,L.CreateDate,S.ID StorehouseID,S.Code StorehouseCode,P.ID ParkID,P.Code ParkCode,SysDept.DeptName RentDeptName", where, page, limit, "L.CreateDate desc");
                returnModel = base.GetReturnModel(tuple.Item1, tuple.Item2);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                LogHelper.Error(new LogInfo() { UserID = UserInfo.UserID, LogType = LogType.Select, LogMessage = "租赁管理" }, ex);
            }
            return Json(returnModel);
        }
        /// <summary>
        /// 添加租赁
        /// </summary>
        /// <param name="id">库位ID</param>
        /// <returns></returns>
        public ActionResult Add(int id)
        {
            ViewBag.LocationID = id;
            return View();
        }
        [HttpPost]
        public JsonResult Add(RentDetail model)
        {
            ReturnModel returnModel = new ReturnModel();
            LogInfo logInfo = new LogInfo() { UserID = base.UserInfo.UserID, LogType = LogType.Insert };
            try
            {
                model.CreateUserID = base.UserInfo.UserID;
                model.CreateDate = DateTime.Now;
                returnModel.count = rentService.RentAdd(model);
                returnModel.msg = "保存成功";
                logInfo.LogMessage = $"新增租赁{returnModel.msg}";
                LogHelper.Info(logInfo);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                returnModel.msg = "保存失败";
                logInfo.LogMessage = $"新增租赁{returnModel.msg}";
                LogHelper.Error(logInfo, ex);
            }
            return Json(returnModel);
        }


        public ActionResult Edit(int? id)
        {
            var model = service.EFGetMany<RentDetail>(e => e.LocationID == id && !e.IsDeleted).FirstOrDefault();
            return View(model);
        }

        [HttpPost]
        public JsonResult Edit(RentDetail model)
        {
            ReturnModel returnModel = new ReturnModel();
            LogInfo logInfo = new LogInfo() { UserID = base.UserInfo.UserID, LogType = LogType.Update };
            try
            {
                var oldModel = service.GetById<RentDetail>(model.ID);
                model.LocationID = oldModel.LocationID;
                model.IsDeleted = oldModel.IsDeleted;
                model.CreateDate = oldModel.CreateDate;
                model.CreateUserID = oldModel.CreateUserID;
                model.LastModifyUserID = base.UserInfo.UserID;
                model.LastModifyDate = DateTime.Now;
                returnModel.count = service.Update(model);
                returnModel.msg = "保存成功";
                logInfo.LogMessage = $"编辑租赁{returnModel.msg}";
                LogHelper.Info(logInfo);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                returnModel.msg = "保存失败";
                logInfo.LogMessage = $"编辑租赁{returnModel.msg}";
                LogHelper.Error(logInfo, ex);
            }
            return Json(returnModel);
        }

        public ActionResult Close(int? id)
        {
            var model = service.EFGetMany<RentDetail>(e => e.LocationID == id && !e.IsDeleted).FirstOrDefault();
            SysDeptService sysDeptService = new SysDeptService();
            var sysDept = sysDeptService.GetById<SysDept>(model.RentDeptID);
            ViewBag.DeptName = sysDept == null ? "" : sysDept.DeptName;
            return View(model);
        }

        /// <summary>
        /// 租赁关闭
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Close(RentDetail model)
        {
            ReturnModel returnModel = new ReturnModel();
            LogInfo logInfo = new LogInfo() { UserID = base.UserInfo.UserID, LogType = LogType.Update };
            try
            {
                var oldModel = service.GetById<RentDetail>(model.ID);
                oldModel.IsDeleted = true;
                oldModel.TrueEndDate = model.TrueEndDate;
                oldModel.NeedPayment = model.NeedPayment;
                oldModel.ActualPayment = model.ActualPayment;
                oldModel.LastModifyUserID = base.UserInfo.UserID;
                oldModel.LastModifyDate = DateTime.Now;
                returnModel.count = rentService.RentClose(oldModel);
                returnModel.msg = "保存成功";
                logInfo.LogMessage = $"结束租赁{returnModel.msg}";
                LogHelper.Info(logInfo);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                returnModel.msg = "保存失败";
                logInfo.LogMessage = $"结束租赁{returnModel.msg}";
                LogHelper.Error(logInfo, ex);
            }
            return Json(returnModel);
        }

        /// <summary>
        /// 租赁推荐
        /// </summary>
        /// <returns></returns>
        public ActionResult Recommend()
        {
            return View();
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Recommend(int page, int limit, V_Rent_Recommend_Query model)
        {
            ReturnModel returnModel = new ReturnModel();
            try
            {
                var where = $"L.IsDeleted=0";// AND L.IsRented=0";
                if (model.Length != 0)
                {
                    where += $" AND L.Length {model.LengthSize} {model.Length}";
                }
                if (model.Width != 0)
                {
                    where += $" AND L.Width {model.WidthSize} {model.Width}";
                }
                if (model.Height != 0)
                {
                    where += $" AND L.Height {model.HeightSize} {model.Height}";
                }
                if (model.StoreTypeID != 0)
                {
                    where += $" AND S.StoreTypeID = {model.StoreTypeID}";
                }
                if (model.Province != 0)
                {
                    where += $" AND P.Province = {model.Province}";
                }
                if (model.City != 0)
                {
                    where += $" AND P.City = {model.City}";
                }
                if (model.County != 0)
                {
                    where += $" AND P.County = {model.County}";
                }
                var tuple = service.GetPageList<V_LocationList>("Location L JOIN Storehouse S ON L.StorehouseID=S.ID JOIN Park P ON L.ParkID=P.ID LEFT JOIN SysDept ON L.RentDeptID=SysDept.ID LEFT JOIN StoreType ST ON S.StoreTypeID=ST.ID", "L.ID,L.Code,L.Area,L.Height,L.Length,L.Width,L.IsRented,L.RentDeptID,L.CreateDate,S.ID StorehouseID,S.Code StorehouseCode,P.ID ParkID,P.Code ParkCode,SysDept.DeptName RentDeptName,P.ProvinceName,P.CityName,P.CountyName,ST.TypeName", where, page, limit, "L.CreateDate desc");
                //var tuple = service.GetPageList<V_LocationList>("Location L JOIN Storehouse S ON L.StorehouseID=S.ID JOIN Park P ON L.ParkID=P.ID LEFT JOIN SysDept ON L.RentDeptID=SysDept.ID LEFT JOIN StoreType ST ON S.StoreTypeID=ST.ID LEFT JOIN (select * from (select ImagePath,LocationID,row_number() over (partition by LocationID order by ID desc) as rownum from LocationImage) temp where rownum = 1) LI ON L.ID=LI.LocationID", "L.ID,L.Code,L.Area,L.Height,L.Length,L.Width,L.IsRented,L.RentDeptID,L.CreateDate,S.ID StorehouseID,S.Code StorehouseCode,P.ID ParkID,P.Code ParkCode,SysDept.DeptName RentDeptName,P.ProvinceName,P.CityName,P.CountyName,ST.TypeName,LI.ImagePath", where, page, limit, "L.CreateDate desc");
                returnModel = base.GetReturnModel(tuple.Item1, tuple.Item2);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                LogHelper.Error(new LogInfo() { UserID = UserInfo.UserID, LogType = LogType.Select, LogMessage = "租赁推荐" }, ex);
            }
            return Json(returnModel);
        }

        public ActionResult History()
        {
            return View();
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult History(int page, int limit)
        {
            ReturnModel returnModel = new ReturnModel();
            try
            {
                var where = "IsDeleted=0";
                //var code = Request.Form["Code"];
                //if (!string.IsNullOrWhiteSpace(code))
                //    where += $" L.Code like '%{code}%'";
                var tuple = service.GetPageList<LocationHistory>("LocationHistory", "*", where, page, limit, "ID desc");
                returnModel = base.GetReturnModel(tuple.Item1, tuple.Item2);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                LogHelper.Error(new LogInfo() { UserID = UserInfo.UserID, LogType = LogType.Select, LogMessage = "租赁历史" }, ex);
            }
            return Json(returnModel);
        }

        [HttpPost]
        [AllowAnonymous]
        public JsonResult RentDept()
        {
            ReturnModel returnModel = new ReturnModel();
            try
            {
                SysDeptService sysDeptService = new SysDeptService();
                var rentDept = sysDeptService.EFGetMany<SysDept>(d => !d.IsDeleted && d.DeptType == 1).Select(s => new { ID = s.ID, DeptName = s.DeptName, DeptCode = s.DeptCode });
                returnModel = base.GetReturnModel(rentDept.Count(), rentDept);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                LogHelper.Error(ex);
            }
            return Json(returnModel);
        }
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <returns></returns>
        public ActionResult FileDownload()
        {
            return View();
        }

        public ActionResult RentAdd()
        {
            return View();
        }

        public ActionResult RentAdd2()
        {
            return View();
        }

        public ActionResult RentNeed()
        {
            return View();
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult RentNeed(int page, int limit)
        {
            ReturnModel returnModel = new ReturnModel();
            try
            {
                var ContactName = Request.Form["ContactName"];
                var where = $"IsDeleted=0";
                if (!string.IsNullOrWhiteSpace(ContactName))
                    where += $" AND ContactName like '%{ContactName}%'";
                var tuple = service.GetPageList<NeedInfo>("NeedInfo", "*", where, page, limit, "CreateDate desc");
                returnModel = base.GetReturnModel(tuple.Item1, tuple.Item2);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                LogHelper.Error(new LogInfo() { UserID = UserInfo.UserID, LogType = LogType.Select, LogMessage = "看仓需求" }, ex);
            }
            return Json(returnModel);
        }
    }
}